package com.test.jbpm.dao.impl;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipInputStream;

import org.jbpm.api.ProcessDefinition;
import org.jbpm.api.ProcessDefinitionQuery;
import org.jbpm.api.RepositoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.test.jbpm.Pager;
import com.test.jbpm.PagerContext;
import com.test.jbpm.dao.ProcessDefinitionDao;


@Repository
public class ProcessDefinitionDaoImpl extends BaseDao implements
		ProcessDefinitionDao {

	private RepositoryService repositoryService;
	
	@Autowired
	public void setRepositoryService(RepositoryService repositoryService) {
		this.repositoryService = repositoryService;
	}

	public Pager<ProcessDefinition> findProcessDefinitionList() {
		List<ProcessDefinition> processDefinitionList = repositoryService.createProcessDefinitionQuery()
//				.processDefinitionName("TroubleTicket")//不要指定是哪个流程，查询全部工作流
				.page(PagerContext.getOffset(), PagerContext.getPageSize())
				.orderDesc(ProcessDefinitionQuery.PROPERTY_VERSION)
				.list();
		long total = repositoryService.createProcessDefinitionQuery().count();
		
		Pager<ProcessDefinition> pager = new Pager<ProcessDefinition>();
		pager.setData(processDefinitionList);
		pager.setTotal(new Long(total).intValue());
		return pager;
	}

	public void add(File processDefinitionFile) {
		try {
			repositoryService.createDeployment()
					.addResourcesFromZipInputStream(
							new ZipInputStream(
									new FileInputStream(processDefinitionFile)))
					.deploy();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}				
	}

	public void del(String deploymentId) {
		repositoryService.deleteDeploymentCascade(deploymentId);
	}

	public InputStream viewImage(String deploymentId, String imageResourceName) {
		return repositoryService.getResourceAsStream(deploymentId, imageResourceName);
	}

	public InputStream viewConent(String deploymentId) {
		String jpdlResourceName = null;
		Set<String> resouceNameSet = repositoryService.getResourceNames(deploymentId);
		for (String resouceName : resouceNameSet) {
			if (resouceName.endsWith(".jpdl.xml")) {
				jpdlResourceName = resouceName;
				break;
			}
		}
		return repositoryService.getResourceAsStream(deploymentId, jpdlResourceName);		
	}
}
